home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 5 / Apprentice-Release5.iso / Source Code / Libraries / VideoToolbox 96.06.15 / (Demos) / TimeVideo.c < prev    next >
Text File  |  1996-05-29  |  48KB  |  1,055 lines

  1. /*
  2. TimeVideo.c
  3. Copyright © Denis G. Pelli, 1992-1996
  4.  
  5. TimeVideo thoroughly tests the timing and synchronization of each video
  6. screen, as well as the integrity of the clut hardware and software, and saves
  7. the results in a self-explanatory text file, “TimeVideo results”. TimeVideo
  8. runs on all Macs, requiring only System 6.05 or better. A discussion
  9. of movies, lookup table animation, and synchronization appears in the
  10. VideoToolbox “Video synch” file. The many video driver bugs uncovered by
  11. TimeVideo and its predecessors are reported in that file. (For example, version 3 of the
  12. TrueVision NuVista driver assumes zero start in 16- and 32-bit depth modes.) Please
  13. add your results by emailing your “TimeVideo results” to denis@xp.psych.nyu.edu.
  14.  
  15. Despite Apple’s rules that require it, a few video drivers don’t allow you to
  16. read the clut (i.e. use cscGetEntries), or crash if you attempt it. GDGetEntries
  17. (in GDVideo.c) checks against a list of known offenders and returns a statusErr
  18. if the cscGetEntries call is not usable. If we can’t use cscGetEntries then we fall back to a
  19. visual test of the clut, comparing a particular way of loading the clut against
  20. the standard way of loading the clut. Any visible change between these two
  21. conditions suggests an error in the non-standard way of loading the clut.
  22.  
  23.     SaveAndRestoreDevice(device);
  24. Each time you call SaveAndRestoreDevice with a device different from the last it
  25. restores the former device to its last state. A NULL device counts as different,
  26. in that it provokes restoration of the previous device. The initial state of this
  27. routine is as though you had just called it with the NULL device.
  28.  
  29. BUGS:
  30. Version 1.0 hung up on a PowerBook 170 with an Envisio video adapter. I didn’t 
  31. have a chance to figure out why. It works fine on my ordinary PowerBook 170.
  32.  
  33. HISTORY:
  34. 8/23/92    dgp    wrote it, based on my TimeCPU.c
  35. 8/26/92    dgp print the driver version only if it's nonzero.
  36.             added summary at end of printout.
  37. 9/9/92    dgp    changed printout of system vbl rate from %.1f to %.2f
  38.             Added movie rate to measurements and printout.
  39. 9/15/92    dgp    made compatible with System 6.04. Added header to results file.
  40. 9/17/92    dgp    Added QUICKLY switch, to select CopyBits or CopyBitsQuickly.
  41. 10/5/92    dgp    cosmetic changes
  42. 10/6/92    dgp    report program version. Use frames/clut update as the criterion for summary.
  43. 10/9/92    dgp    Fixed summary. Too slow means MORE than one frame per clut update.
  44.             Fixed restoration of clut in direct modes (i.e. 16 and 32 bit modes).
  45.             Renamed to GDRestoreDeviceClut and put it in GDVideo.c.
  46. 10/13/92 dgp Tom Busey reported that frames were going uncounted
  47.             during the clut timing, which seems to be a problem with some video drivers.
  48.             TimeVideo now reports a frame count based solely on timing in secs and
  49.             the separately measured frame rate, which seems to be a reliable.
  50.             It also double checks the timing in secs vs frames, and if
  51.             it finds a discrepancy, prints a warning to the screen & file. 
  52. 10/20/92 dgp Added VBL/frame to summary.
  53. 12/8/92    dgp Minor editing of comments.
  54. 12/9/92    dgp    1.01 Added _atexit(RestoreCluts) in case user quits prematurely.
  55. 12/11/92 dgp 1.02 GDRestoreBlackAndWhite allocates stack space for linearTable
  56.             only if we need it.
  57. 12/30/92 dgp 1.03 cosmetic changes.
  58. 12/30/92 dgp 1.04 Enhanced summary to account for NAN when no clut access is allowed.
  59. 12/30/92 dgp 1.05 Use GDClutSize().
  60. 1/6/93    dgp     1.06 Simplified GDRestoreBlackAndWhite, eliminated linearTable.
  61. 1/7/93    dgp  1.07 Included in VideoToolbox-1-93.sea
  62. 1/8/93    dgp     1.08 Added Info-Mac to report file.
  63. 1/11/93    dgp     1.09 In response to bug report from jonathan brecher, added support
  64.             for computers that lack Color QuickDraw.
  65. 1/15/93    dgp    1.10 Added version resource.
  66. 1/18/93    dgp    1.11 Updated the explanatory text.
  67. 1/24/93 dgp    1.12 Updated the explanatory text.
  68. 2/6/93 dgp    1.13 Report ROM version.
  69. 2/15/93 dgp    1.14 Report ROM version as 124+6*256.
  70. 2/22/93    dgp    1.15 Recompiled.
  71. 2/27/93    dgp    1.16 Recompiled with new Identify.c.
  72. 3/10/93    dgp    1.17 Choose a valid mode for which to print the frame rate.
  73.                  Moved all the timing code into GDInfo.c, so this routine just prints.
  74. 3/12/93    dgp        Reorganized the printout and added TestCluts's capabilities.
  75. 3/13/93    dgp        Added high-priority timing.
  76. 3/16/93    dgp    2.0 Added visual hash inspection.
  77. 3/31/93    dgp    2.1 Release version, clut test seems to work.
  78. 4/5/93    dgp    2.2 Recognize gray1 error.
  79. 4/6/93    dgp    2.3 Remove assumption that mode numbers imply certain number of bits.
  80. 4/13/93    dgp    2.3.1 Only set results file type when it is created, not when appending.
  81. 4/15/93    dgp        Display Testing window with gray wedge on test screen.
  82. 4/16/93    dgp    2.4b Restore compatibility with 1-bit qd.
  83. 4/19/93    dgp    2.4.1b Support old Mac II 24-bit NuBus addressing. Fixed two places
  84.                 where I used garbage in place of a linear color table when
  85.                 gdType==directType. Use new GDNewLinearColorTable.
  86. 4/19/93    dgp    2.4.2b Estimate color transformation matrix.
  87. 4/19/93    dgp    2.4.3b Use color transformation matrix to assess gray error.
  88. 4/19/93    dgp    2.4.4b Fixed RectToAddress to always return a 32-bit address,
  89.                     so it won't crash under System 6.
  90. 4/25/93    dgp    2.4.5b Correct for -0.5 bias in estimating rgb gains in TestClut.c
  91. 4/25/93    dgp    2.4.6b Test both color and gray modes; tolerance=3 lsb.
  92. 4/25/93    dgp    2.4.7b Worked around New Palette Manager bugs in original 32-bit QD.
  93. 4/27/93    dgp    2.4.8b Fixed stale-cache bug in SetPixelsQuickly. Cleaned up mode
  94.                     indexing.
  95. 4/28/93    dgp 2.4.9b Rewrote code dealing with SetDepth and HasDepth, wrote GDHasMode().
  96.                     Ignore "isGray" for 16 and 32-bit modes.
  97. 5/11/93    dgp 2.4.9bb Fixed bug in GDTestClutHash in GDTestClut.c in response to bug 
  98.                 report by Jonathan Brecher.
  99. 5/17/93    dgp 2.4.9bbb Changed SetEntriesQuickly to respect the color/gray mode of device.
  100. 5/18/93    dgp 2.4.9b4 Check that card->device is not NULL.
  101. 5/18/93    dgp 2.4.9b5 Suppress printing of identity color transformation.
  102. 5/18/93    dgp 2.4.9b6 Note that 16 and 32 bit depths are always in color mode.
  103. 5/18/93    dgp 2.5 Release version.
  104. 6/2/93    dgp 2.5.1 Updated text reference to info-mac.
  105. 7/7/93    dgp 2.5.2 Recompiled with new GDDacSize, for compatibility with
  106.                 Radius PowerView.
  107. 1/13/94    dgp 2.5.3 Updated description of VideoToolbox.
  108. 6/7/94    dgp    3.0.0 New C-based version of CopyBitsQuickly. Fixed versions of CopyBitsQuickly,
  109.                 SetPixelsQuickly, and SetEntriesQuickly that are compatible with dirty ROMs.
  110. 6/14/94    dgp    3.0.1 Copy Monaco-font style resource from application into the "TimeVideo report"
  111.                 document.
  112. 6/19/94    dgp    3.0.2 Various cosmetic changes, recompile with latest CopyBitsQuickly and 
  113.                 SetEntriesQuickly.
  114. 7/8/94    dgp    3.0.3 Recompiled with new THINK C 7.03.
  115. 7/29/94 dgp Eliminated use of "#s" printf format, since it's not supported by
  116.             Metrowerks CodeWarrior C.
  117. 8/1/94    dgp 3.0.4 Recompiled with latest sources.
  118. 8/14/94    dgp Added workaround for [][][][!isGray] bug in Metrowerks CodeWarrior compiler.
  119. 9/5/94 dgp removed assumption in printf's that int==short.
  120. 10/12/94 dgp Used Metrowerks CodeWarrior C to produce fat binary.
  121. 10/20/94 dgp 3.5 Defined BLANKLINE in GDInfo.h to work around bug in 
  122.         Metrowerks CW4.5 bug in handling of \r.
  123. 11/17/94    dgp    3.6 updated the text describing VideoToolbox.
  124. 11/17/94    dgp 3.6.1 added explanation of “GDSetEntries ... NAN ... frames”.
  125. 11/30/94    dgp Use Display Manager to test all display modes. Untested.
  126. 12/29/94 dgp 3.6.2 WriteAndReadClut now waits for vbl before reading.
  127. 1/7/95    dgp 3.6.3 Got Display Manager calls to work.
  128. 3/18/94 dgp 3.6.4 Recompiled with CodeWarrior 5.5, which supposedly fixs some C bugs.
  129. 3/22/95 dgp 3.6.5 Added check for bad Dome driver, and enhanced detection of CW compiler version.
  130. 4/1/95 dgp Updated my address. Added advice about how to interpret cscSetEntries/cscGetEntries 
  131.             errors.
  132. 4/7/95 dgp 3.6.6 Read A7 draft of "Designing Cards & Drivers for Power Mac Computers", and
  133.             added support for multiple resolutions on PCI Macs. 
  134. 4/8/95 dgp 3.7.0 Polished the explanatory text that appears at the beginning of the results file.
  135.             Disabled WAIT_FOR_VBL in WriteAndReadClut() in GDTestClut.c.
  136. 4/18/95 dgp Call SVersion() only if _SlotManager trap is available.
  137. 5/27/95 dgp cosmetic corrections. Print blank line at beginning of PrintVideoInfo.
  138.             Recompile with CodeWarrior 6.
  139. 6/14/95 dgp 3.7.2 recompile with new less-wordy version of IdentifyMachine().
  140. 6/24/95 dgp 3.7.3 updated URL from info-mac/dev/src/ to info-mac/dev/lib/.
  141. 9/9/95 dgp updated URL from ...372 to ...373.
  142. 9/18/95 dgp deleted Syracuse address.
  143. 10/5/95 dgp 3.7.4 recompiled with new GDVideo.c:GDCardName that checks for Slot Manager first, for
  144.         compatibility with PCI Macs.
  145. 10/6/95 dgp changed default to normally NOT do the visual tests.
  146. 10/14/95 dgp fixed bug reported by Brian McElree and Beau Watson whereby requesting tests at
  147.             multiple resolutions on a PCI Mac resulted in no testing at all. The bug was due
  148.             to my erroneous assumption that PCI Macs would not have a Slot Manager. 
  149.             Now scan PCI device list even if the Slot Manager is present. Recompiled with 
  150.             new Identify.c functions that work on PCI bus (they call UseNameRegistery.c).
  151. 10/24/95 dgp dropped ".fat" from name of application. Now prefer the mirror.apple.com ftp site.
  152. 10/25/95 dgp added Caution about multiple resolutions.
  153. 3/7/96 dgp Fixed TestCLUT.c to reflect fact that cscSetEntries reads from table[0],.... whereas 
  154.         cscGetEntries writes to table[start],.... 
  155. 3/7/96 dgp 3.7.5 note whether VM, RAMDoubler, or FileSharing is on.
  156. 3/26/96 dgp 3.7.6 increase tolerance for recognizing identity, allow insignificant bits to be garbage.
  157.             Changed "notIsGray" to "!isGray". This was an obsolete work-around for a compiler bug.
  158. 5/28/96    dgp    added conditional UNIVERSAL_INTERFACES_VERSION<0x0212.    
  159. */
  160. #define VERSION "3.7.6"
  161. #include "VideoToolbox.h"
  162. #ifndef __TRAPS__
  163.     #include <Traps.h>
  164. #endif
  165. #include <ROMDefs.h>    // catDisplay,typeVideo
  166. #include "GDInfo.h"
  167. void TimeVideo(void);
  168. char *IdentifyMachineAndType(void);
  169. void PrintVideoInfo(FILE *o[2],VideoInfo *card);
  170. void ReportRGBGains(FILE *o[2],Boolean quickly,Boolean isGray,VideoInfo *card);
  171. long GDColors(GDHandle device);
  172. char setEntriesString[][18]={"cscSetEntries","SetEntriesQuickly"};
  173. char colorGrayString[][6]={"color","gray"};
  174. char ColorGrayString[][6]={"Color","Gray"};
  175. #if UNIVERSAL_HEADERS
  176.     #ifndef __DISPLAYS__
  177.         #include <Displays.h>
  178.     #endif
  179. #else
  180.     enum{kDMDriverNotDisplayMgrAwareErr = -6228};
  181.     extern pascal OSErr DMSetDisplayMode(GDHandle theDevice,unsigned long mode
  182.         ,unsigned long *depthMode,unsigned long reserved,Handle displayState)
  183.          ={0x303C,0x0A11,0xABEB};
  184.     extern pascal OSErr DMCheckDisplayMode(GDHandle theDevice,unsigned long mode
  185.         ,unsigned long depthMode,unsigned long *switchFlags,unsigned long reserved
  186.         ,Boolean *modeOk)={0x303C,0x0C12,0xABEB};
  187.     enum {
  188.         gestaltDisplayMgrAttr        = 'dply',    /* Display Manager attributes */
  189.         gestaltDisplayMgrPresent    = 0            /* True if Display Mgr is present */
  190.     };
  191. #endif
  192.  
  193. /* 
  194. These enum definitions for use with the cscGetNextResolution driver status call 
  195. are taken from Apple's Designing PCI Cards and Drivers for
  196. Power Mac Computers. These enum definitions ought to be in Video.h, 
  197. but they aren't, as of version 2.1 (ETO18). They ARE in version 2.12 (ETO20).
  198. UNIVERSAL_INTERFACES_VERSION is defined in Apple's ConditionalMacros.h, but only
  199. since version 2.1, which was distributed with CodeWarrior 8.
  200. */
  201. #if UNIVERSAL_INTERFACES_VERSION<0x0212
  202.     enum{
  203.         kDisplayModeIDCurrent=0
  204.         ,kDisplayModeIDInvalid=0xffffffff
  205.         ,kDisplayModeIDFindFirstResolution=0xfffffffe
  206.         ,kDisplayModeIDNoMoreResolutions=0xfffffffd
  207.     };
  208. #endif
  209.  
  210. void SaveAndRestoreDevice(GDHandle device);
  211. OSErr GDSetDelay(GDHandle device,Boolean dontWaitForVBL,double nanoseconds);
  212. OSErr GDGetDelay(GDHandle device,Boolean *dontWaitForVBLPtr,double *nanosecondsPtr);
  213.  
  214. void main(void)
  215. {
  216.     StackGrow(40000L+MAX_SCREENS*sizeof(VideoInfo));
  217.     Require(gestaltOriginalQD);
  218.     TimeVideo();
  219. }
  220.  
  221. // new routines in Identify.c, based on Apple's new NameRegistry
  222. void GetCPUProperties(char *cpuName,long *cpuHz,Boolean *hasL2Cache);
  223. void GetVideoProperties(GDHandle device,char *slotName,char *cardName,char *cardModel);
  224.  
  225. void TimeVideo(void)
  226. {
  227.     long system;
  228.     static unsigned long v[256],colorMax;
  229.     FILE *o[2],*dataFile;
  230.     int newDataFile;
  231.     unsigned long time;
  232.     Str255 todayStr;
  233.     int i,j,d,error;
  234.     int cards,width,height;
  235.     int quickly,isGray,doTest,ok;
  236.     Rect r,screenRect;
  237.     WindowPtr window;
  238.     VideoInfo *card;
  239.     Handle rsrc;
  240.     int rsrcFile;
  241.     long value;
  242.     SpBlock spBlock;
  243.     short flags;
  244.     static char string[1024],datafilename[]="TimeVideo results";
  245.     Boolean doVisualTests,displayMgrOk,slotMgrPresent,testMultipleResolutions;
  246.     
  247.     assert(StackSpace()>5000);
  248.     MaximizeConsoleHeight();
  249.     #if (THINK_C || THINK_CPLUS || SYMANTEC_C)
  250.         console_options.title="\pTimeVideo";
  251.     #endif
  252.     printf("\n");    // ask THINK C to initialize quickdraw
  253.  
  254.     if(0){ // just for debugging.
  255.         GDHandle device=NULL;
  256.         char cpuName[128];
  257.         long cpuHz;
  258.         Boolean hasL2Cache;
  259.         char slotName[128],cardName[128],cardModel[128];
  260.  
  261.         GetCPUProperties(cpuName,&cpuHz,&hasL2Cache);
  262.         printf("%s, %ld MHz, cache?=%d\n",cpuName,cpuHz/1000000,hasL2Cache);
  263.         for(i=0;;i++){
  264.             device=GetScreenDevice(i);
  265.             if(device==NULL)break;
  266.             GetVideoProperties(device,slotName,cardName,cardModel);
  267.             printf("%s, %s, %s\n",slotName,cardName,cardModel);
  268.             printf("%s\n",IdentifyVideo(device));
  269.         }
  270.         printf("%s\n",BreakLines(IdentifyMachine(),78));
  271.         IdentifyMachine();
  272.         exit(1);
  273.     }
  274.     GetDateTime(&time);
  275.     srand(time);
  276.     srandU(time);
  277.     printf("%s","Welcome to TimeVideo " VERSION "\n");
  278.     printf("%s\n\n",BreakLines(IdentifyMachine(),78));
  279.     sprintf(string,
  280.     "This program will thoroughly test all your video devices and save the "
  281.     "results in the text file “%s”. Don’t be alarmed by the strange "
  282.     "antics of your screens. Everything will soon be back to normal. Just sit back "
  283.     "and enjoy the show.",datafilename);
  284.     sprintf(string,"%s You may quit at any time by hitting Command-period.\n",string);
  285.     printf(BreakLines(string,78));
  286.     if(1)printf(BreakLines("\n"
  287.         "TimeVideo times everything: the video frames, interrupts, and cluts. And it "
  288.         "determines what fraction of the screen you can fill with a real-time movie shown "
  289.         "by CopyBits() or CopyBitsQuickly(). Then it does write-then-read tests of the "
  290.         "clut, to make sure the video hardware and software "
  291.         "are working correctly.\n",78));
  292.  
  293.     if(1){    // Adjust the PowerMac 7500/8500 video driver CLUT timing
  294.         GDHandle device=NULL;
  295.         double nanoseconds=999;
  296.         Boolean adjust=0,dontWaitForVBL=-1;
  297.  
  298.         device=GetScreenDevice(0);
  299.         error=GDGetDelay(device,&dontWaitForVBL,&nanoseconds);
  300.         if(!error){
  301.             printf("\n%s\n",IdentifyVideo(device));
  302.             printf("[GDGetDelay:CLUT timing: dontWaitForVBL=%d, delay %.0f ns per rgb triplet]\n",(int)dontWaitForVBL,nanoseconds);
  303.             adjust=Choose(0,"Would you like to adjust the CLUT timing of this video driver?\n",noYes,2);
  304.         }else adjust=0;
  305.         if(adjust){
  306.             dontWaitForVBL=!Choose(1,"Wait for VBL when loading CLUT?\n",noYes,2);
  307.             nanoseconds=800;
  308.             printf("How many ns delay per RGB triplet? (%.0f)",nanoseconds);
  309.             gets(string);
  310.             sscanf(string,"%lf",&nanoseconds);
  311.             error=GDSetDelay(device,dontWaitForVBL,nanoseconds);
  312.             if(error)printf("GDSetDelay error %d\n",(int)error);
  313.             if(1){
  314.                 error=GDGetDelay(device,&dontWaitForVBL,&nanoseconds);
  315.                 if(error)printf("GDGetDelay error %d\n",(int)error);
  316.                 else printf("[GDGetDelay:CLUT timing: dontWaitForVBL=%d, delay %.0f ns per rgb triplet]\n"
  317.                     "These settings will persist until you restart your computer.\n"
  318.                     ,(int)dontWaitForVBL,nanoseconds);
  319.             }
  320.         }
  321.     }
  322.     doVisualTests=Choose(0,"\nWould you like the testing to pause for visual inspections?\n",noYes,2);
  323.     value=0;
  324.     Gestalt(gestaltDisplayMgrAttr,&value);
  325.     displayMgrOk=value&(1<<gestaltDisplayMgrPresent);
  326.     if(displayMgrOk)
  327.         printf("%s",BreakLines("\n(Caution: testing multiple resolutions may fail, especially if the video driver " 
  328.         "offers more than seven resolutions, leaving your display in "
  329.         "whatever resolution was then being tested. I hope to fix this in the next version. dgp.)\n",78));
  330.     if(displayMgrOk)
  331.         testMultipleResolutions=Choose(0,"Test multiple resolutions of each display?\n",noYes,2);
  332.     else testMultipleResolutions=0;
  333.  
  334.     printf("\n");
  335.     dataFile=fopen(datafilename,"r");
  336.     newDataFile=(dataFile==NULL);
  337.     if(newDataFile){
  338.         // try to copy SimpleText style resource from TimeVideo application into our document.
  339.         rsrc=GetResource('styl',128);
  340.         if(rsrc!=NULL){
  341.             c2pstr(datafilename);
  342.             CreateResFile((unsigned char *)datafilename);
  343.             rsrcFile=OpenResFile((unsigned char *)datafilename);
  344.             p2cstr((unsigned char *)datafilename);
  345.             if(rsrcFile!=-1){
  346.                 DetachResource(rsrc);
  347.                 UseResFile(rsrcFile);
  348.                 AddResource(rsrc,'styl',128,(ConstStr255Param)"/pTimeVideo report style");
  349.                 CloseResFile(rsrcFile);
  350.             }else ReleaseResource(rsrc);
  351.         }
  352.     }else fclose(dataFile);
  353.     o[0]=stdout;
  354.     o[1]=dataFile=fopen(datafilename,"a");    /* Append to data file */
  355.     if(dataFile==NULL){
  356.         printf("Could neither open nor create “%s”. Perhaps your disk is locked.\n"
  357.             ,datafilename);
  358.         newDataFile=0;
  359.     }
  360.     if(newDataFile){
  361.         SetFileInfo(datafilename,'TEXT','ttxt');
  362.         fprintf(dataFile,BreakLines(
  363.         "This file reports the timing and accuracy of all your video screens, "
  364.         "as measured by TimeVideo, a component of the VideoToolbox. "
  365.         "TimeVideo runs on all Macs, requiring only System 6.05 or better. To quickly "
  366.         "test a large number of computers, run TimeVideo from a floppy disk; "
  367.         "all the results will accumulate in a single results file. TimeVideo is "
  368.         "free, and may be freely distributed. You can get the latest version from:\n"
  369.         "ftp://mirror.apple.com/mirrors/info-mac/cfg/time-video-376.hqx\n"
  370.         "\nTHE VIDEO TOOLBOX\n"
  371.         "The VideoToolbox is a collection of two hundred C subroutines and "
  372.         "several demo and utility programs that I and others have written to do "
  373.         "visual psychophysics with Macintosh computers. It is fully compatible "
  374.         "with 680x0 and PowerPC Macs and with Metrowerks CodeWarrior C and "
  375.         "Symantec C compilers. It's free and may not be sold without "
  376.         "permission. It should be useful to anyone who wants to present "
  377.         "accurately specified visual stimuli or use the Mac for psychometric "
  378.         "experiments. The text file \"Video synch\" discusses all the ways of "
  379.         "synchronizing programs to video displays and the many pitfalls to avoid. "
  380.         "The TimeVideo application checks out the timing of all video devices in "
  381.         "anticipation of their use in critical real-time applications, e.g. "
  382.         "movies or lookup table animation. Low-level routines control video "
  383.         "timing and lookup tables, display real-time movies, and implement the "
  384.         "luminance-control algorithms suggested by Pelli and Zhang (1991). (D.G. "
  385.         "Pelli and L. Zhang, 1991, \"Accurate control of contrast on "
  386.         "microcomputer displays.\" Vision Research, 31, 1337-1350. Reprints are "
  387.         "available.) In particular, GetPixelsQuickly and SetPixelsQuickly peek "
  388.         "and poke pixels in bitmaps and pixmaps, CopyBitsQuickly and CopyWindows "
  389.         "faithfully copy between bit/pixmaps and the screen, WindowToEPS saves an "
  390.         "image to disk, for later printing or incorporation into a document, and "
  391.         "SetEntriesQuickly and GDSetEntries load the screen's color lookup table, "
  392.         "all without any of QuickDraw's color translations. High-level routines "
  393.         "help analyze psychophysical experiments (e.g. graphing or "
  394.         "maximum-likelihood fitting of psychometric data). Assign.c is a runtime "
  395.         "C interpreter for C assignment statements, which is useful for "
  396.         "controlling experiments and sharing calibration data. "
  397.         "Many of the routines are Mac-specific, but some very "
  398.         "useful routines, e.g. the luminance-control, statistics, "
  399.         "maximum-likelihood fitting algorithms, and the runtime interpreter are "
  400.         "written in Standard C and will work on any computer. "
  401.         "Documentation is in the source files themselves. "
  402.         "This collection has been continually updated since 1991. "
  403.         "You can download the latest version of "
  404.         "\"video-toolbox\" from a public archive, e.g.:\n"
  405.         "ftp://sumex-aim.stanford.edu/info-mac/dev/lib/\n"
  406.         "ftp://mirror.apple.com/mirrors/info-mac/dev/lib/\n"
  407.         "ftp://mirrors.aol.com/pub/info-mac/dev/lib/\n"
  408.         "ftp://src.doc.ic.ac.uk/packages/mac/info-mac/dev/lib/\n"
  409.         "ftp://ftp.stolaf.edu/pub/macpsych/\n"
  410.         "CompuServe://MacDev forum/Library 4 \"C and Pascal\"/VIDEOT.SEA\n"
  411.         "Or you can request a file by email; for instructions send a query to "
  412.         "Info-Mac-Request@sumex-aim.stanford.edu."
  413.         "\n\nTo get future versions automatically, just send me your name and email address. "
  414.         "Each time I post a new version of the VideoToolbox to the Info-Mac "
  415.         "Archives, I email a copy to everyone on the subscription list; there are "
  416.         "currently over 170 subscribers. (Let me know if you prefer notification only, "
  417.         "without the 3 MB enclosure.)\n",78));
  418.     fprintf(dataFile, "%s\n\n",
  419.         BreakLines("Denis Pelli, denis@psych.nyu.edu, "
  420.         "Psychology Dept., New York University, "
  421.         "6 Washington Place, New York, NY 10003, USA",78));
  422.     fprintf(dataFile,BreakLines(
  423.         "\nTIME VIDEO\n"
  424.         "Other than reading and writing pixels, all access to a video device normally goes "
  425.         "through the software video driver. (You can use VideoToolbox SetEntriesQuickly.c "
  426.         "to bypass the video driver of a few devices, but I don't recommend that, except "
  427.         "as a last resort, because your program will then only work with the few video "
  428.         "devices that SetEntriesQuickly.c supports.) The video driver is normally supplied "
  429.         "in ROM on the video card or, for built-in video, in the computer's ROM. "
  430.         "(Apparently, new PCI drivers can simply be tossed onto the System Folder.) Many "
  431.         "drivers have subtle bugs that TimeVideo has uncovered and documented. A complete "
  432.         "list of all known video driver bugs appears in the \"Video bugs\" document included "
  433.         "in the VideoToolbox archive described above. Please send new bugs to "
  434.         "denis@psych.nyu.edu\n\n"
  435.         "For each video card, TimeVideo measures the video frame rate, frequency of VBL "
  436.         "interrupts (ought to be one per frame), how long it takes to load the clut "
  437.         "(ought to be one frame or less), "
  438.         "and how much of the screen you can fill with a real-time one-image-per-frame "
  439.         "movie shown by CopyBits() or CopyBitsQuickly(). It then performs a random "
  440.         "write-then-read test of the Color Lookup Table (clut). This tests the clut "
  441.         "memory hardware and the software used to write and read the clut. We test "
  442.         "writing by GDSetEntries(), which makes a cscSetEntries call to the video driver, and, "
  443.         "if possible, we also test writing by SetEntriesQuickly(), which accesses the hardware "
  444.         "directly. (SetEntriesQuickly supports only a few video cards.) "
  445.         "In either case, the clut is read by GDGetEntries, "
  446.         "which makes a cscGetEntries call to the video driver. "
  447.         "The testing is thorough; many video devices fail "
  448.         "at least part of the test. All the driver errors uncovered to date appear in the "
  449.         "VideoToolbox \"Video bugs\" text file, and have been reported to the video card's "
  450.         "manufacturer. Add your results by emailing this file to "
  451.         "denis@psych.nyu.edu\n"
  452.         "\nHappily, we don't know of any cases of errors in cscSetEntries itself, "
  453.         "and we've never run across a hardware failure of the CLUT memory. "
  454.         "Our experience is that errors in the cscSetEntries/cscGetEntries write-then-read "
  455.         "test of the CLUT occur in two ways: "
  456.         "\n1. The driver does not implement cscSetGamma and the fixed gamma table is "
  457.         "not the identity transformation, i.e. \"uncorrected gamma table\". "
  458.         "TimeVideo always calls cscSetGamma, requesting an identity transform. "
  459.         "In all drivers, the RGB values supplied in a cscSetEntries call "
  460.         "are transformed by the gamma table before being loaded into the CLUT. "
  461.         "The presence of a non-identity "
  462.         "gamma table is usually obvious from a glance at the color matrix, since the gains "
  463.         "in the matrix will exceed 1 by about twice the fractional rms error indicated by ±%%."
  464.         "\n2. The CLUT is set correctly, but the driver incorrectly implements cscGetEntries. "
  465.         "Bugs in cscGetEntries are usually obvious from a glance at the color matrix, "
  466.         "e.g. nonzero gains off the diagonal, or the pattern of errors.\n\n"
  467.  
  468.         "The video driver on the PowerMac 7500 and 8500 supresses the VBL interrupt while it's "
  469.         "loading the CLUT, so any VBL-frame-counting task will miss an interrupt each time "
  470.         "you call cscSetEntries to load the clut. Calling cscSetEntries once per frame to "
  471.         "synchronize your code with the frame should still work fine, but it'll be slightly tricky "
  472.         "to check for overrun (i.e. taking too long between cscSetEntries calls), since a "
  473.         "simple VBL-interrupt-based frame counter will run differently on different Macs.\n\n"
  474.  
  475.         "Errors reported by TimeVideo are usually due to bugs in the video driver software "
  476.         "in the ROM of the video card (or built-in video device). If the bug will "
  477.         "interfere with your experiments, "
  478.         "then to use the card (or built-in video) you must either fix/replace the driver or "
  479.         "bypass the driver, using SetEntriesQuickly to access the hardware directly "
  480.         "(if SetEntriesQuickly supports it). "
  481.         "I suggest that you try replacing the driver, because this will keep your "
  482.         "software hardware-independent. The VideoToolbox \"Video synch\" document explains "
  483.         "how to fix the the Mac IIci video driver, patching or replacing the buggy version "
  484.         "0 .Display_Video_Apple_RBV1 driver by copying the bug-free version 1 of the same "
  485.         "driver from the Mac IIsi. It is very likely that an analogous approach "
  486.         "could be used to fix/replace the buggy version 0, 1, and 2 .Display_Video_Apple_DAFB "
  487.         "drivers in the Quadra 700, 750, and 900, by the bug-free version 3 or 5 of that driver "
  488.         "in the Centris 650 or the LC 475. And please report your bugs; the bug-free revised drivers "
  489.         "are probably the result of our past bug reports.\n"
  490.         "\nGLOSSARY\n"
  491.         "A video frame is a complete refresh of your video screen. (With interlacing it takes "
  492.         "two fields to do a complete refresh, i.e. a frame, but graphics displays usually are "
  493.         "not interlaced and have a single field per frame.) To show a movie, you will want "
  494.         "to reload the image once per frame; the table shows how big that image can be, "
  495.         "as a fraction of the screen area, and still be reloaded once per frame. "
  496.         "(Some video cards have multiple video \"pages\"--call GDGetPageCnt()--that "
  497.         "can be switched by calling GDSetPageDrawn() and GDSetPageShown().) "
  498.         "A \"VBL\" "
  499.         "interrupt is produced by your video card, nominally once per frame, but "
  500.         "some video cards produce more, which is poor, but not serious. (The "
  501.         "VBLInstall.c program will deal with it.) Suppressed interrupts during clut "
  502.         "updates are bad. It means that the driver disables the VBL interrupt for too "
  503.         "long while it's loading the clut. This will throw off any interrupt-based "
  504.         "attempt to count frames. (The clut is the color lookup table of your video card.) "
  505.         "Lookup table animation, e.g. for temporal modulation of contrast, requires that "
  506.         "you reload the clut once per frame, so it's very important that this be fast "
  507.         "enough. "
  508.         "The first call to SetEntriesQuickly() for each device is slow--a cache is "
  509.         "filled; the reported times are for subsequent calls. "
  510.         "Each video card can be in \"Color\" or \"Gray\" mode, as set by the Control "
  511.         "Panel:Monitors or the Macintosh Toolbox call SetDepth(). "
  512.         "In \"Gray\" mode all colors are transformed to luminance-equivalent "
  513.         "grays. This is done by the video driver, when loading the clut, "
  514.         "but only if the pixelSize≤8. "
  515.         "TimeVideo does a linear regression on the results of write-then-read tests of the CLUT "
  516.         "to measure the driver's color transformation matrix. It reports the matrix "
  517.         "if it is other than the identity transformation:\n"
  518.         "(ROut) (1 0 0) (RIn)\n"
  519.         "(GOut)=(0 1 0)x(GIn)\n"
  520.         "(BOut) (0 0 1) (BIn)\n"
  521.         "The clut tests try loading the clut serially, one entry at a time, and "
  522.         "all at once; some video drivers fail the serial test. For more explanation see "
  523.         "the text file called \"Video synch\" on the VideoToolbox disk.\n"
  524.         "\n"
  525.         "\"cscSetEntries ... NAN ... frames\"= the driver refuses to load the CLUT.\n" 
  526.         "\"ok\"= passed all tests.\n"
  527.         "\"!gray\"= passed the color test, but is supposed to be in gray mode.\n"
  528.         "\"!color\"= passed the gray test, but is supposed to be in color mode.\n"
  529.         "\"!serial\"= passed when loaded all at once, but failed when loaded serially.\n"
  530.         "\"bad\"= read did not equal write and the error is reported explicitly.\n"
  531.         "We know that SetEntriesQuickly is \"!serial\" on the Quadra, alas.\n"
  532.         "\nThis is a SimpleText document using the Monaco font to line up the \n"
  533.         "columns properly.\n\n",78));
  534.     }
  535.     ffprintf(o,"TimeVideo version " VERSION "\n");
  536.     GetDateTime(&time);
  537.     IUDateString(time,longDate,todayStr);
  538.     ffprintf(o,"%s.\n",p2cstr(todayStr));
  539.     ffprintf(o,"%s\n",IdentifyCompiler());
  540.     if(strlen(IdentifyVM())>0)ffprintf(o,"%s\n",IdentifyVM());
  541.     if(IsFileSharingOn())ffprintf(o,"File Sharing is on.\n");
  542.  
  543.     // Timer.c requires the Revised Time Manager, which appeared in System 6.0.3.
  544.     // SetDepth() is part of the "new" Palette Manager, which appeared in System 6.0.5.
  545.     Gestalt(gestaltSystemVersion,&system);
  546.     if(system<0x605)PrintfExit("Sorry. Your System is too old; I need at least System 6.0.5.\n");
  547.     card=(VideoInfo *)NewPtrClear(MAX_SCREENS*sizeof(*card));
  548.     if(card==NULL)PrintfExit("Need more memory. "
  549.         "Use Finder's File:Get Info to increase TimeVideo's allocation.\n");
  550.     ffprintf(o,"%s\n",BreakLines(IdentifyMachineAndType(),78));
  551.     if(o[1]!=NULL){
  552.         //fprintf(o[1],"Tick rate is %.1f Hz. ",TickRate());
  553.         //fprintf(o[1],"System-based VBL rate is %.1f Hz.\n",GDFrameRate(NULL));
  554.     }
  555.     if(QD8Exists())_atexit(RestoreCluts);// In case user quits prematurely.
  556.     if(TrapAvailable(_SlotManager))slotMgrPresent=(SVersion(&spBlock)==noErr);
  557.     else slotMgrPresent=0;
  558.     spBlock.spSlot=0;
  559.     spBlock.spID=0;
  560.     for(i=0;;i++){
  561.         if(QD8Exists()){
  562.             if(testMultipleResolutions){ // index through the display modes, one by one
  563.                 unsigned long currentDisplayModeID,depthModeUL,switchFlags;
  564.                 Boolean modeOk;
  565.                 unsigned long horizontalPixels,verticalLines;    // not used
  566.                 Fixed refreshRate;                                // not used
  567.                 unsigned short maxDepthMode;                    // not used
  568.                 static int deviceCounter=0;
  569.                 static unsigned long displayModeID=kDisplayModeIDFindFirstResolution;
  570.                 Boolean useSlotMgr;
  571.             
  572.                 useSlotMgr=slotMgrPresent;
  573.                 if(slotMgrPresent){                    
  574.                     spBlock.spExtDev=0;
  575.                     spBlock.spHwDev=0;
  576.                     spBlock.spCategory=catDisplay;
  577.                     spBlock.spCType=typeVideo;
  578.                 }
  579.             nextDisplayModeID:
  580.                 if(useSlotMgr){
  581.                     // NuBus or no bus: use slot manager to find every driver displayModeID
  582.                     spBlock.spTBMask=3;        // ignore DrvrHW and DrvrSW
  583.                     spBlock.spParamData=1;    // next resource, any slot, whether enabled or disabled
  584.                     error=SGetTypeSRsrc(&spBlock);
  585.                     if(error){
  586.                         // done
  587.                         if(displayModeID!=kDisplayModeIDFindFirstResolution)
  588.                             SaveAndRestoreDevice(NULL);
  589.                         useSlotMgr=0;
  590.                         goto checkPCIBus;
  591.                     }
  592.                     displayModeID=(unsigned char)spBlock.spID;    // "resource reference number"
  593.                     if(spBlock.spRefNum==0){
  594.                         spBlock.spTBMask=2;        // ignore DrvrSW
  595.                         spBlock.spParamData=2;    // find enabled resource in same slot with same DrvrHW
  596.                         spBlock.spID=0;
  597.                         error=SGetTypeSRsrc(&spBlock);
  598.                         if(error)goto nextDisplayModeID;
  599.                         spBlock.spID=displayModeID;    // restore
  600.                     }
  601.                     card[i].device=GetDeviceByRefNum(spBlock.spRefNum);
  602.                     SaveAndRestoreDevice(card[i].device);
  603.                     if(card[i].device==NULL)goto nextDisplayModeID;
  604.                 }
  605.                 checkPCIBus:
  606.                 if(!useSlotMgr){
  607.                     // PCI bus: use new driver calls to test each displayModeID of each driver
  608.                     card[i].device=GetScreenDevice(deviceCounter);
  609.                     SaveAndRestoreDevice(card[i].device);
  610.                     if(card[i].device==NULL)break;    // no more video devices; go home.
  611.                     error=GDGetNextResolution(card[i].device,displayModeID
  612.                         ,&displayModeID,&horizontalPixels,&verticalLines
  613.                         ,&refreshRate,&maxDepthMode);
  614.                     if(error || displayModeID==kDisplayModeIDNoMoreResolutions
  615.                         || displayModeID==kDisplayModeIDInvalid){
  616.                         deviceCounter++;
  617.                         displayModeID=kDisplayModeIDFindFirstResolution;
  618.                         // error merely indicates that driver doesn't support the Display Manager
  619.                         if(error)goto testDeviceAnyway;
  620.                         goto nextDisplayModeID;
  621.                     }
  622.                 }
  623.                 error=DMCheckDisplayMode(card[i].device,displayModeID,firstVidMode,&switchFlags,0,&modeOk);
  624.                 if(!modeOk)goto nextDisplayModeID;
  625.                 error=GDGetDisplayMode(card[i].device,¤tDisplayModeID,NULL,NULL,NULL);
  626.                 if(error || currentDisplayModeID!=displayModeID){
  627.                     depthModeUL=firstVidMode;
  628.                     error=DMSetDisplayMode(card[i].device,displayModeID,&depthModeUL,0,NULL);
  629.                     if(error==kDMDriverNotDisplayMgrAwareErr)goto testDeviceAnyway;
  630.                     if(error)goto nextDisplayModeID;
  631.                 }
  632.             testDeviceAnyway:;
  633.             }else{
  634.                 // index through the video devices
  635.                 card[i].device=GetScreenDevice(i);
  636.                 SaveAndRestoreDevice(card[i].device);
  637.                 if(card[i].device==NULL)break;
  638.             }
  639.         }else card[i].device=NULL;
  640.         ffprintf(o,"\n%s\n",BreakLines(IdentifyVideo(card[i].device),78));
  641.         if(card[i].device==GetMainDevice()){
  642.             // Print out info from special call for PowerMac 7500/8500 built-in video driver
  643.             double nanoseconds;
  644.             Boolean dontWaitForVBL;
  645.  
  646.             error=GDGetDelay(card[i].device,&dontWaitForVBL,&nanoseconds);
  647.             if(!error)ffprintf(o,"[GDGetDelay:CLUT timing: dontWaitForVBL=%d, delay %.0f ns per rgb triplet]\n",(int)dontWaitForVBL,nanoseconds);
  648.         }
  649.         printf("Getting card info. . ." "\r");
  650.         error=GDInfo(&card[i]);
  651.         
  652.         // Specify what tests we want.
  653.         for(d=0;d<6;d++)for(quickly=0;quickly<2;quickly++)for(isGray=0;isGray<2;isGray++){
  654.             card[i].depth[d].clut[quickly][isGray].read.doTest=1;
  655.         }
  656.         if(card[i].device!=NULL)isGray=!TestDeviceAttribute(card[i].device,gdDevType);
  657.         else isGray=0;
  658.         // Further test deepest directType and clutType modes
  659.         d=5;
  660.         while(card[i].depth[d].pixelSize>=0 && card[i].depth[d].pixelSize<16)d--;
  661.         if(d>=0)for(quickly=0;quickly<2;quickly++){
  662.             card[i].depth[d].clut[quickly][isGray].hash.doTest=doVisualTests;
  663.             card[i].depth[d].clut[quickly][!isGray].read.doTest=1;
  664.         }
  665.         d=3;
  666.         while(card[i].depth[d].pixelSize==0 || card[i].depth[d].pixelSize>8)d--;
  667.         if(d>=0)for(quickly=0;quickly<2;quickly++){
  668.             card[i].depth[d].clut[quickly][isGray].hash.doTest=doVisualTests;
  669.             card[i].depth[d].clut[quickly][!isGray].read.doTest=1;
  670.         }
  671.  
  672.         // Open window
  673.         if(QD8Exists()){
  674.             r=screenRect=(*card[i].device)->gdRect;
  675.         }else{
  676.             CopyQuickDrawGlobals();    // make sure qd is valid.
  677.             r=screenRect=qd.screenBits.bounds;
  678.         }
  679.         OffsetRect(&r,-r.left,-r.top);
  680.         width=(r.right/=3);
  681.         if(width>256)width=r.right=256;
  682.         height=r.bottom=width;
  683.         CenterRectInRect(&r,&screenRect);
  684.         if(QD8Exists())window=(WindowPtr)NewCWindow(NULL,&r,"\pCLUT Colors",TRUE,noGrowDocProc,(WindowPtr) -1L,0,0);
  685.         else window=NewWindow(NULL,&r,"\pTesting",TRUE,noGrowDocProc,(WindowPtr) -1L,0,0);
  686.             
  687.         for(d=0;d<6;d++)for(isGray=0;isGray<2;isGray++){
  688.             if(card[i].depth[d].pixelSize==0)continue;
  689.             doTest=0;
  690.             for(quickly=0;quickly<2;quickly++){
  691.                 doTest|=card[i].depth[d].clut[quickly][isGray].read.doTest;
  692.                 doTest|=card[i].depth[d].clut[quickly][isGray].hash.doTest;
  693.                 doTest|=card[i].depth[d].clut[quickly][isGray].visual.doTest;
  694.             }
  695.             if(!doTest)continue;
  696.             if(card[i].device!=NULL){
  697.                 if(card[i].depth[d].mode!=(**card[i].device).gdMode
  698.                     || isGray!=!TestDeviceAttribute(card[i].device,gdDevType)){
  699.                     // On Mac IIci, Sys 6.07, HasDepth returns "mode" of 0x100 
  700.                     // at all legal depths.
  701.                     if(card[i].depth[d].pixelSize>0)
  702.                         ok=HasDepth(card[i].device,card[i].depth[d].pixelSize,1,!isGray);
  703.                     else ok=1;
  704.                     // Mac IIci Sys 6.07: SetDepth only accepts mode, not pixelSize.
  705.                     if(ok)error=SetDepth(card[i].device,card[i].depth[d].mode,1,!isGray);
  706.                     if(card[i].depth[d].mode!=(**card[i].device).gdMode
  707.                         || isGray!=!TestDeviceAttribute(card[i].device,gdDevType))continue;
  708.                 }
  709.             }else if(card[i].depth[d].pixelSize!=1 || isGray)continue;
  710.             GDInfo(&card[i]);
  711.             
  712.             // Fill window with spectrum of all colors.
  713.             colorMax=GDColors(card[i].device)-1;
  714.             for(j=0;j<width;j++)v[j]=(j*colorMax+width/2)/(width-1);
  715.             for(j=0;j<height;j++)SetWindowPixelsQuickly(window,0,j,v,width);
  716.             
  717.             if(!card[i].depth[d].timeTested){
  718.                 error=GDInfoTime(&card[i]);
  719.                 for(j=0;j<height;j++)SetWindowPixelsQuickly(window,0,j,v,width);//refresh
  720.             }
  721.             for(quickly=0;quickly<2;quickly++){
  722.                 printf(BLANKLINE);
  723.                 printf("%d-bit %s pixels: testing clut: %s . . ." "\r"
  724.                     ,(int)card[i].depth[d].pixelSize,colorGrayString[isGray]
  725.                     ,setEntriesString[quickly]);
  726.                 if(quickly)flags=testClutQuicklyFlag;
  727.                 else flags=0;
  728.                 error=GDTestClut(o,flags,&card[i]);
  729.                 error=GDTestClut(o,flags|testClutSeriallyFlag,&card[i]);
  730.                 error=GDTestClutHash(flags,&card[i]);
  731.             }
  732.         }
  733.         DisposeWindow(window);
  734.         if(QD8Exists()){
  735.             // On Mac IIci, Sys 6.07, HasDepth returns "mode" of 0x100 at all legal depths.
  736.             // and SetDepth only accepts mode, not depth.
  737. //            ok=HasDepth(card[i].device,oldPixelSize,1,oldIsColor);
  738. //            if(ok)error=SetDepth(card[i].device,oldDepthMode,1,oldIsColor);
  739.         }
  740.         printf(BLANKLINE);
  741.         printf("Getting card info. . ." "\r");
  742.         error=GDInfo(&card[i]);
  743.         printf(BLANKLINE);
  744.         PrintVideoInfo(o,&card[i]);
  745.         if(dataFile!=NULL)fflush(dataFile);
  746.         if(kbhit())getcharUnbuffered();    // Give console a chance to detect Command-.
  747.         if(!QD8Exists())break;
  748.     }
  749.     cards=i;
  750.     if(GDVersion(card[i].device)==100
  751.         && EqualString("\p.Display_Video_Apple_RBV1",GDName(card[i].device),1,1)){
  752.             ffprintf(o,
  753.             "NOTE: the built-in driver in the Mac IIci (.Display_Video_Apple_RBV1 version 0)\n"
  754.             "has a bug that causes it to crash if you attempt to read the clut. A temporary\n"
  755.             "patch has been applied that has fixed the driver until the next reboot, as\n"
  756.             "explained in the VideoToolbox document \"Video synch\".\n");
  757.     }
  758.     if(dataFile!=NULL){
  759.         fprintf(dataFile,"\n\n");
  760.         fclose(dataFile);
  761.         printf(BreakLines("\nTimeVideo is free, and may be freely distributed. "
  762.             "You can get the latest version from:\n"
  763.             "ftp://mirror.apple.com/mirrors/info-mac/cfg/time-video-376.hqx\n",78));
  764.         sprintf(string,"\nThe text file \"%s\" explains all the results.\n",datafilename);
  765.         printf(BreakLines(string,78));
  766.     }
  767.     DisposePtr((Ptr)card);
  768. }
  769.  
  770. void PrintVideoInfo(FILE *o[2],VideoInfo *card)
  771. {
  772.     short i,d,tested,quickly,isGray,grayClut,reportRGB;
  773.     char string[100];
  774.     static char s1[]="%-33s",s2[]="%6s",s3[]="  %-9s\n";
  775.     VideoCardClutTest *clut;
  776.     
  777.     printf("\r"    "          " "          " "          " "          "
  778.         "          " "          " "          " "          " "\r");
  779.     if(card->device!=NULL)isGray=!TestDeviceAttribute(card->device,gdDevType);
  780.     else isGray=0;
  781.     ffprintf(o,"%d-bit dacs. ",(int)card->dacSize);
  782.     ffprintf(o,"%dx%d pixels. ",(int)card->width,(int)card->height);
  783. //    ffprintf(o,"%s mode. ",ColorGrayString[isGray]);
  784.     ffprintf(o,"\n");
  785.  
  786.     if(card->basicTested){
  787.         ffprintf(o,s1,"pixel size");
  788.         for(d=0;d<6;d++)if(card->depth[d].pixelSize){
  789.             sprintf(string,"%d   ",(int)card->depth[d].pixelSize);
  790.             ffprintf(o,s2,string);
  791.         }
  792.         ffprintf(o,s3,"bits");
  793.     
  794.         if(QD8Exists()){
  795.             // I haven't tried to look for 1-bit QD's page swapping scheme
  796.             ffprintf(o,s1,"pages");
  797.             for(d=0;d<6;d++)if(card->depth[d].pixelSize){
  798.                 sprintf(string,"%d   ",(int)card->depth[d].pages);
  799.                 ffprintf(o,s2,string);
  800.             }
  801.             ffprintf(o,s3,"");
  802.     
  803.             // Meaningless in 1-bit QD
  804.             ffprintf(o,s1,"mode");
  805.             for(d=0;d<6;d++)if(card->depth[d].pixelSize){
  806.                 sprintf(string,"0x%x ",card->depth[d].mode);
  807.                 ffprintf(o,s2,string);
  808.             }
  809.             ffprintf(o,s3,"");
  810.         }
  811.     }
  812.  
  813.     if(card->timeTested){
  814.         ffprintf(o,s1,"frame rate");
  815.         for(d=0;d<6;d++)if(card->depth[d].pixelSize){
  816.             sprintf(string,"%.1f ",card->depth[d].frameRate);
  817.             ffprintf(o,s2,string);
  818.         }
  819.         ffprintf(o,s3,"Hz");
  820.     
  821.         ffprintf(o,s1,"interrupts per frame");
  822.         for(d=0;d<6;d++)if(card->depth[d].pixelSize){
  823.             sprintf(string,"%.1f ",card->depth[d].vblPerFrame);
  824.             ffprintf(o,s2,string);
  825.         }
  826.         ffprintf(o,s3,"");
  827.     
  828.         ffprintf(o,s1,"CopyBits movie size");
  829.         for(d=0;d<6;d++)if(card->depth[d].pixelSize){
  830.             sprintf(string,"%.2f",card->depth[d].movieRate/card->depth[d].frameRate);
  831.             ffprintf(o,s2,string);
  832.         }
  833.         ffprintf(o,s3,"screen");
  834.     
  835.         ffprintf(o,s1,"CopyBitsQuickly movie size");
  836.         for(d=0;d<6;d++)if(card->depth[d].pixelSize){
  837.             sprintf(string,"%.2f",card->depth[d].movieRateQuickly/card->depth[d].frameRate);
  838.             ffprintf(o,s2,string);
  839.         }
  840.         ffprintf(o,s3,"screen");
  841.     
  842.         ffprintf(o,s1,"CopyBits data rate");
  843.         for(d=0;d<6;d++)if(card->depth[d].pixelSize){
  844.             sprintf(string,"%.2f",card->depth[d].movieRate
  845.                 *card->depth[d].pixelSize
  846.                 *card->width*card->height/8./1024./1024.);
  847.             ffprintf(o,s2,string);
  848.         }
  849.         ffprintf(o,s3,"MB/s");
  850.     
  851.         ffprintf(o,s1,"CopyBitsQuickly data rate");
  852.         for(d=0;d<6;d++)if(card->depth[d].pixelSize){
  853.             sprintf(string,"%.2f",card->depth[d].movieRateQuickly
  854.                 *card->depth[d].pixelSize
  855.                 *card->width*card->height/8./1024./1024.);
  856.             ffprintf(o,s2,string);
  857.         }
  858.         ffprintf(o,s3,"MB/s");
  859.     }
  860.     
  861.     if(card->device!=NULL && (**card->device).gdType!=fixedType && card->timeTested){
  862.         ffprintf(o,s1,"cscSetEntries duration");
  863.         for(d=0;d<6;d++)if(card->depth[d].pixelSize){
  864.             sprintf(string,"%.2f",card->depth[d].framesPerClutUpdate);
  865.             ffprintf(o,s2,string);
  866.         }
  867.         ffprintf(o,s3,"frames");
  868.  
  869.         ffprintf(o,s1,"cscSetEntries suppresses ints.for");
  870.         for(d=0;d<6;d++)if(card->depth[d].pixelSize){
  871.             sprintf(string,"%.1f ",card->depth[d].missingFramesPerClutUpdate);
  872.             ffprintf(o,s2,string);
  873.         }
  874.         ffprintf(o,s3,"frames");
  875.  
  876.         ffprintf(o,s1,"GDSetEntriesHighPriority duration");
  877.         for(d=0;d<6;d++)if(card->depth[d].pixelSize){
  878.             sprintf(string,"%.2f",card->depth[d].framesPerClutUpdateHighPriority);
  879.             ffprintf(o,s2,string);
  880.         }
  881.         ffprintf(o,s3,"frames");
  882.  
  883.         if(card->setEntriesQuickly){
  884.             ffprintf(o,s1,"SetEntriesQuickly duration");
  885.             for(d=0;d<6;d++)if(card->depth[d].pixelSize){
  886.                 sprintf(string,"%.2f",card->depth[d].framesPerClutUpdateQuickly);
  887.                 ffprintf(o,s2,string);
  888.             }
  889.             ffprintf(o,s3,"frames");
  890.         }
  891.     }
  892.     if(card->device!=NULL && (**card->device).gdType!=fixedType && card->clutTested){
  893.         for(quickly=0;quickly<2;quickly++)for(isGray=0;isGray<2;isGray++){
  894.             tested=0;
  895.             for(d=0;d<6;d++)if(card->depth[d].pixelSize)
  896.                 if(card->depth[d].clut[quickly][isGray].hash.tested)tested=1;
  897.             if(tested){
  898.                 sprintf(string,"%s hash inspection",setEntriesString[quickly]);
  899.                 ffprintf(o,s1,string);
  900.                 for(d=0;d<6;d++)if(card->depth[d].pixelSize){
  901.                     clut=&card->depth[d].clut[quickly][isGray];
  902.                     if(clut->hash.tested){
  903.                         if(clut->hash.errors)
  904.                             sprintf(string,"fail");
  905.                         else sprintf(string,"ok");
  906.                     }else sprintf(string,"");
  907.                     ffprintf(o,s2,string);
  908.                 }
  909.                 ffprintf(o,s3,"");
  910.             }
  911.         }
  912.     
  913.         for(quickly=0;quickly<2;quickly++)for(isGray=0;isGray<2;isGray++){
  914.             tested=0;
  915.             for(d=0;d<6;d++)if(card->depth[d].pixelSize)
  916.                 if(card->depth[d].clut[quickly][isGray].read.tested)tested=1;
  917.             if(tested){
  918.                 reportRGB=0;
  919.                 sprintf(string,"%s: %s test"
  920.                     ,colorGrayString[isGray],setEntriesString[quickly]);
  921.                 ffprintf(o,s1,string);
  922.                 for(d=0;d<6;d++)if(card->depth[d].pixelSize){
  923.                     clut=&card->depth[d].clut[quickly][isGray];
  924.                     grayClut=isGray && card->depth[d].pixelSize<=8;
  925.                     if(clut->read.tested){
  926.                         if(clut->read.errors){
  927.                             if(clut->read.errorsAtOnce)sprintf(string,"bad");
  928.                             else sprintf(string,"!serial");
  929.                         }else if(grayClut!=clut->read.identity)sprintf(string,"ok");
  930.                         else sprintf(string,"!%s",colorGrayString[grayClut]);
  931.                     }else sprintf(string,"");
  932.                     ffprintf(o,s2,string);
  933.                     if(card->depth[d].pixelSize<=8)reportRGB=!clut->read.identity;
  934.                 }
  935.                 ffprintf(o,s3,"");
  936.                 if(reportRGB)ReportRGBGains(o,quickly,isGray,card);
  937.             }
  938.     
  939.             tested=0;
  940.             for(d=0;d<6;d++)if(card->depth[d].pixelSize)
  941.                 if(card->depth[d].clut[quickly][isGray].visual.tested)tested=1;
  942.             if(tested){
  943.                 sprintf(string,"%s visual inspection",setEntriesString[quickly]);
  944.                 ffprintf(o,s1,string);
  945.                 for(d=0;d<6;d++)if(card->depth[d].pixelSize){
  946.                     clut=&card->depth[d].clut[quickly][isGray];
  947.                     if(clut->visual.tested){
  948.                         if(clut->visual.errors){
  949.                             if(!clut->visual.errorsAtOnce)sprintf(string,"!serial");
  950.                             else sprintf(string,"bad");
  951.                         }else sprintf(string,"ok");
  952.                     }else sprintf(string,"");
  953.                     ffprintf(o,s2,string);
  954.                 }
  955.                 ffprintf(o,s3,"");
  956.             }
  957.         }
  958.     }
  959.     for(i=0;i<2;i++)if(o[i]!=NULL)fflush(o[i]);    // Save to disk, just in case.
  960. }
  961.  
  962. // Print a 3x3 color matrix representing a best fit to the observed relation between
  963. // the colors we read and the colors we write.
  964. void ReportRGBGains(FILE *o[2],Boolean quickly,Boolean isGray,VideoInfo *card)
  965. {
  966.     short j,k,d,depths;
  967.     VideoCardClutTest *clut;
  968.     double rgbGain[3][3],rgbError[3];
  969.     Boolean integralGains,bad;
  970.  
  971.     depths=0;
  972.     for(j=0;j<3;j++){
  973.         for(k=0;k<3;k++)rgbGain[j][k]=0.;
  974.         rgbError[j]=0.0;
  975.     }
  976.     integralGains=1;
  977.     for(d=0;d<6;d++)if(card->depth[d].pixelSize && card->depth[d].pixelSize<=8){
  978.         clut=&card->depth[d].clut[quickly][isGray];
  979.         bad=0;
  980.         for(j=0;j<3;j++)bad|=clut->read.rgbError[j]>2.0*(1<<(16-4));
  981.         if(bad)continue;
  982.         for(j=0;j<3;j++){
  983.             for(k=0;k<3;k++)rgbGain[j][k]+=clut->read.rgbGain[j][k];
  984.             rgbError[j]+=clut->read.rgbError[j];
  985.         }
  986.         depths++;
  987.     }
  988.     for(j=0;j<3;j++){
  989.         for(k=0;k<3;k++){
  990.             rgbGain[j][k]/=depths;
  991.             integralGains&=(rgbGain[j][k]==floor(rgbGain[j][k]));
  992.         }
  993.         rgbError[j]/=depths;
  994.     }
  995.     if(IsFinite(rgbGain[0][0]))for(j=0;j<3;j++){
  996.         ffprintf(o," (%cOut±%4.1f%%)%c"
  997.             ,"RGB"[j],rgbError[j]*100./USHRT_MAX," = "[j]);
  998.         if(integralGains)ffprintf(o,"(%1.0f %1.0f %1.0f)"
  999.             ,rgbGain[j][0],rgbGain[j][1],rgbGain[j][2]);
  1000.         else ffprintf(o,"(%3.2f %3.2f %3.2f)"
  1001.             ,rgbGain[j][0],rgbGain[j][1],rgbGain[j][2]);
  1002.         ffprintf(o,"%c(%cIn)\n"," x "[j],"RGB"[j]);
  1003.     }
  1004. }
  1005.  
  1006. // On Mac IIci, Sys 6.07, HasDepth returns "mode" of 0x100 at all legal depths.
  1007. // and SetDepth only accepts mode, not depth.
  1008. //            ok=HasDepth(card[i].device,oldPixelSize,1,oldIsColor);
  1009. //            if(ok)error=SetDepth(card[i].device,oldDepthMode,1,oldIsColor);
  1010.  
  1011. void SaveAndRestoreDevice(GDHandle device)
  1012. {
  1013.     static Boolean firstTime=1,displayMgrOk,colorQdOk;
  1014.     static GDHandle oldDevice=NULL;
  1015.     static unsigned short oldDepthMode=firstVidMode,oldIsColor=1;
  1016.     static unsigned long oldDisplayModeID=kDisplayModeIDInvalid,displayModeID;
  1017.     unsigned long depthModeUL;
  1018.     int error;
  1019.     long value;
  1020.  
  1021.     if(firstTime){
  1022.         Gestalt(gestaltSystemVersion,&value);
  1023.         assert(value>=0x605);    // need New Palette Manager for SetDepth
  1024.         Gestalt(gestaltQuickdrawVersion,&value);
  1025.         colorQdOk=value>=gestalt8BitQD;
  1026.         value=0;
  1027.         Gestalt(gestaltDisplayMgrAttr,&value);
  1028.         displayMgrOk=value&(1<<gestaltDisplayMgrPresent);
  1029.         firstTime=0;
  1030.     }
  1031.     if(colorQdOk && device!=oldDevice){
  1032.         // restore old device to old state
  1033.         if(oldDevice!=NULL){
  1034.             if(displayMgrOk && oldDisplayModeID!=kDisplayModeIDInvalid){
  1035.                 error=GDGetDisplayMode(oldDevice,&displayModeID,NULL,NULL,NULL);
  1036.                 if(displayModeID!=oldDisplayModeID){
  1037.                     depthModeUL=oldDepthMode;
  1038.                     error=DMSetDisplayMode(oldDevice,oldDisplayModeID,&depthModeUL,0,NULL);
  1039.                 }
  1040.             }
  1041.             error=SetDepth(oldDevice,oldDepthMode,1,oldIsColor);
  1042.         }
  1043.         // save old state of new device
  1044.         oldDevice=device;
  1045.         oldDisplayModeID=kDisplayModeIDInvalid;    // default, in case call fails
  1046.         if(oldDevice!=NULL){
  1047.             if(displayMgrOk)
  1048.                 error=GDGetDisplayMode(oldDevice,&oldDisplayModeID,&oldDepthMode,NULL,NULL);
  1049.             oldDepthMode=(**device).gdMode;
  1050.             oldIsColor=TestDeviceAttribute(device,gdDevType);
  1051.         }
  1052.     }
  1053. }
  1054.  
  1055.